#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>

int main()
{
  int pipefd[2]={0};
//创建管道
  int ret=pipe(pipefd);
  if(ret<0){
    perror("pipe error");
    return -1;
  }

  pid_t ps_pid=fork();
  if(ps_pid==0){
    close(pipefd[0]);    //只是写入，关闭读端
    dup2(pipefd[1],1);  //将标准输出重定向到管道写入端，则此时向标准输出端写入数据==向管道中写入数据
    execlp("ps","ps","-ef",NULL);
    exit(-1);
  }

  pid_t grep_pid=fork();
  if(grep_pid==0){
    close(pipefd[1]); //读端，关闭写端
    dup2(pipefd[0],0);  //将标准输入重定向到管道读取端,则此时从标准输入读取数据==从管道读取数据  
    execlp("grep","grep","pipe",NULL);
    exit(-1);
  }


  //父进程中关闭读写端
  close(pipefd[0]);
  close(pipefd[1]);

  waitpid(ps_pid,NULL,0);
  waitpid(grep_pid,NULL,0);

  return 0;
}
